package com.guli.vod.service.Impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.guli.commonutils.R;
import com.guli.servicebase.exceptionhandler.GuliException;
import com.guli.vod.service.VodService;
import com.guli.vod.utils.ConstantVodUtils;
import com.guli.vod.utils.initVod;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

@Service
public class VodServiceImpl implements VodService {

    @Override
    public String uploadVideoAly(MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename(); //文件原始名称
            String title = fileName.substring(0, fileName.lastIndexOf('.')); //文件上传后显示的名称
            InputStream inputStream = file.getInputStream();
            UploadStreamRequest request = new UploadStreamRequest(ConstantVodUtils.ACCESS_KEY_ID,
                    ConstantVodUtils.ACCESS_KEY_SECRET, title, fileName, inputStream);
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
            String videoId = response.getVideoId();
            return videoId;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public void removeMoreAlyVideo(List videoIdList) {
        try {
            //初始化对象
            DefaultAcsClient client =
                    initVod.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            //创建删除视频的request对象
            DeleteVideoRequest request = new DeleteVideoRequest();

            //将集合中的值转换为字符串，由，拼接
            String videos = StringUtils.join(videoIdList.toArray(), ",");
            //设置视频id
            request.setVideoIds(videos);
            //调用删除方法
            client.getAcsResponse(request);
        } catch (Exception e) {
            throw new GuliException(20001, "删除失败");
        }
    }
}